import axios from "axios";
import React, { useRef, useState } from "react";

interface PropsType {
  children: string | JSX.Element;
  beforeUpload?: (file: File) => boolean;
  action: string;
  onChange?: (change: any) => void
}

export const MyUpload: React.FC<PropsType> = ({
  children,
  beforeUpload,
  action,
  onChange: change
}) => {
  const inputRef = useRef<HTMLInputElement | null>(null);
  const onChange = async () => {
    const input = inputRef.current as HTMLInputElement;
    const files = input.files as FileList;
    const file = files[0];

    if (beforeUpload && !beforeUpload(file)) {
      return;
    }
    // 创建formData
    const formData = new FormData();
    // 添加数据
    formData.append("file", file, file.name);

    // 验证通过
    const result = await axios.post(action, formData);
    change && change(result)
  };

  return (
    <div>
      <input
        type="file"
        ref={inputRef}
        style={{ display: "none" }}
        onChange={() => onChange()}
      />
      <div onClick={() => inputRef.current?.click()}>{children}</div>
    </div>
  );
};
